<?php
require_once(dirname(__FILE__).'/../../../upgrade.php');
class create_catassoc_history_table extends UPGRADE
{
	/**
	* IsAlreadyUpgraded
	* Do we need to run this classes upgrade script or not ?
	*
	* @return bool true if the upgrade has already run, otherwise false
	*/
	function IsAlreadyUpgraded()
	{
		return $this->TableExists($GLOBALS['tablePrefix'].'catassoc_history');
	}

	/**
	* Upgrade
	* Do the actual upgrade of this component. If this is successful all
	* subsequent calls to IsAlreadyUpgraded should return true
	*
	* @return void
	*/
	function Upgrade()
	{
		$query = "
			CREATE TABLE `".$GLOBALS['tablePrefix']."catassoc_history` (
				`categoryid` int(11) NOT NULL default '0',
				`questionid` int(11) NOT NULL default '0',
				 UNIQUE KEY `idx_uqcah_pk` (`categoryid`,`questionid`),
				 KEY `idx_cah_qcatids` (`questionid`,`categoryid`)
			) ENGINE=MyISAM
		";			
		$result = $GLOBALS['AKB_DB']->Query($query);
		
		$query = "SELECT ca.categoryid, ca.questionid "
		. "FROM ".$GLOBALS['tablePrefix']."categoryassociations ca , "
		. $GLOBALS['tablePrefix']."questions q "
		. "WHERE q.questionid = ca.questionid "
		. "AND q.workflowstatus != 'pending' ";
		$result = $GLOBALS['AKB_DB']->Query($query);
		while ($row = $GLOBALS['AKB_DB']->Fetch($result)) {
				$insertQuery = "INSERT INTO ".$GLOBALS['tablePrefix']."catassoc_history (categoryid,questionid) values ('".$row['categoryid']."','".$row['questionid']."')";
				$insertResult = $GLOBALS['AKB_DB']->Query($insertQuery);
		}

		
	}

}
?>
